<!-- 部门管理 部门列表组件 -->
<template>
  <div class="">
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator="/">
      <!-- <el-breadcrumb-item><a>用户管理</a></el-breadcrumb-item> -->
      <el-breadcrumb-item>路由权限管理</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <el-form :model="queryInfo" ref="queryForm" size="small" :inline="true" label-width="90px">
        <el-form-item label="接口URI" prop="uri">
          <el-input v-model="queryInfo.uri" placeholder="请输入接口URI" clearable />
        </el-form-item>
        <el-form-item label="是否白名单" prop="isExclude">
          <el-select v-model="queryInfo.isExclude" placeholder="是否白名单" clearable style="width: 240px">
            <el-option label="是" value="y">是</el-option>
            <el-option label="否" value="n">否</el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleQuery" type="primary" icon="el-icon-search" size="mini">搜索</el-button>
          <el-button @click="resetQuery" icon="el-icon-refresh" size="mini">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8" style="marginBottom:20px">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="addTaskHandle">新增</el-button>
        </el-col>
        <el-col :span="1.5"> </el-col>
        <el-col :span="1.5">
          <!-- <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="deleteTaskHandle">删除</el-button> -->
        </el-col>
        <el-col :span="1.5">
          <!-- <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button> -->
        </el-col>
      </el-row>

      <el-table :data="userList" tooltip-effect="dark" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column prop="createUser" label="创建者"> </el-table-column>
        <el-table-column prop="createTime" label="创建时间"> </el-table-column>
        <el-table-column prop="uri" label="url"> </el-table-column>
        <el-table-column prop="checkStrategy" label="校验策略">
          <!-- 校验策略 or：或者，and：并且 -->
          <template slot-scope="scope">
            <span :value="scope.row.checkStrategy">{{
              scope.row.checkStrategy === 'or' ? '或者' : '并且'
            }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注信息"> </el-table-column>
        <el-table-column prop="updateTime" label="更新时间"> </el-table-column>
        <el-table-column prop="isExclude" label="是否白名单" align="center">
          <!-- 是否过滤 y：过滤，n：拦截 -->
          <template slot-scope="scope">
            <span :value="scope.row.isExclude">{{
              scope.row.isExclude === 'y' ? '是' : '否'
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="220" class-name="small-padding fixed-width">
          <template v-if="scope.row.userId !== 1" slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="updateTaskHandle(scope.row)">修改</el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="deleteTaskHandle(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="queryInfo.currentPage" :page-sizes="[10, 20, 30, 40]" :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </el-card>

    <!-- 添加修改用户 弹窗 -->
    <el-dialog :title="upload.title" width="600px"  :visible.sync="dialogVisible" @close="addDialogClosed">
      <!-- 内容主题区域 -->
      <el-form ref="addFormRef" :model="addForm" :rules="addFormRules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="接口url" prop="uri">
              <!--   非数组次联 一对多 数据源: UrlOptions    -->
              <el-cascader :options="UrlOptions"
                filterable
                :filter-method="filterMethod"
                :props="{  value: 'uri', label: 'controllerName', children: 'mappings',disabled:'isRecord'}"
                :show-all-levels="false"
                v-model="addForm.uri"
                @change="hanldeChangeCascader"
                ref="myCascader"
                >
              </el-cascader>
            <!-- <el-option
                  v-for="(item, index) in UrlOptions"
                  :key="index"
                  :label="item.controllerName"
                  :value="item.controllerName"
                >
                  <el-popover placement="right" width="180"  trigger="hover">
                    <span slot="reference"  class="urlSpan"> {{ item.controllerName }}</span>
                    <div v-if="item.mappings">
                      <div v-for="item2 in item.mappings" :key="item.uri">
                        {{ item2.mappingName }}
                      </div>
                    </div>
                  </el-popover>
                  </el-option> -->
            <!-- <div v-for="(item,index) in UrlOptions" :key="index">
                   </div> -->
              <!-- </el-select> -->
            </el-form-item>
          </el-col>
          <el-col :span="13">
            <el-form-item label="是否白名单" prop="isExclude" label-width="100px">
              <el-radio-group v-model="addForm.isExclude">
                <el-radio label="y">是</el-radio>
                <el-radio label="n">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="addForm.isExclude=='n'">
            <el-form-item label="权限集合" prop="permissions">
              <el-cascader v-model="addForm.permissions" :options="listOptions" :props="{
                multiple: true,
                checkStrictly: true,
                value: 'menuId',
                label: 'menuName',
                children: 'children'
              }" clearable ref="cascaderAddr"
              ></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="addForm.isExclude=='n'">
            <el-form-item label="校验策略" prop="checkStrategy">
              <el-radio-group v-model="addForm.checkStrategy" >
                <el-radio label="or">或者</el-radio>
                <el-radio label="and">并且</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="addForm.remark"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 路由日志详细 -->
    <el-dialog title="路由详细" :visible.sync="openView" width="700px" append-to-body>
      <el-form ref="form" :model="form" label-width="120px" size="mini">
        <el-row>
          <el-col :span="12">
            <el-form-item label="路由编号：">{{ detail.jobId }}</el-form-item>
            <el-form-item label="路由名称：">{{ detail.jobName }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="路由分组：">{{
              detail.jobGroup
            }}</el-form-item>
            <el-form-item label="创建时间：">{{
              detail.createTime
            }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="cron表达式：">{{
              detail.cronExpression
            }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="下次执行时间：">{{
              detail.nextTime
            }}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="调用目标字符串：">{{
              detail.invokeTarget
            }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="路由状态：">
              <div v-if="detail.status == 0">正常</div>
              <div v-else-if="form.detail == 1">失败</div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否并发：">
              <div v-if="detail.concurrent == 0">允许</div>
              <div v-else-if="detail.concurrent == 1">禁止</div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="执行策略：">
              <div v-if="detail.misfirePolicy == 0">默认策略</div>
              <div v-else-if="detail.misfirePolicy == 1">立即执行</div>
              <div v-else-if="detail.misfirePolicy == 2">执行一次</div>
              <div v-else-if="detail.misfirePolicy == 3">放弃执行</div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="openView = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  // 组件名称
  name: '',
  // 局部注册的组件
  components: {},
  // 组件参数 接收来自父组件的数据
  props: {},
  // 组件状态值
  data() {
    return {
      UrlOptions: [],
      listOptions: [],
      routerId: undefined,
      // 多选选中的数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      form: {},
      // showSearch: true,
      detail: {}, // 路由详情
      // 获取用户列表数据的参数对象
      queryInfo: {
        // 当前的页数
        currentPage: 1,
        // 当前每页显示多少条数据
        pageSize: 10,
        jobName: undefined,
        jobGroup: undefined,
        status: undefined
      },
      userList: [],
      total: 0,
      rowData: {},
      // 对话框显示与隐藏
      dialogVisible: false,
      // 是否显示详细弹出层
      openView: false,
      // 表单参数
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0
      },
      // 添加用户的表单数据
      addForm: {
        isExclude: '',
        checkStrategy: '',
        permissions:[]

      },
         // 表单校验
      addFormRules: {
        permissions: [
          { required: true, message: "权限集合不能为空", trigger: "blur" },
        ],
        checkStrategy:[
          { required: true, message: "校验策略不能为空", trigger: "blur" },
        ],
        isExclude:[
          { required: true, message: "是否白名单不能为空", trigger: "blur" },
        ],
        uri:[
          { required: true, message: "接口url不能为空", trigger: "blur" },
        ],

      },

    }
  },
  // 计算属性
  computed: {},
  // 侦听器
  watch: {},
  created() {
    this.getList()
    this.getRoleList()
  },
  methods: {
    // 搜索下拉框 用value 模糊查询
    filterMethod(node, searchValue) {
      return (
        node.label.includes(searchValue) ||
        node.value.includes(searchValue)
      );
     },
    // 定时路由列表
    async getList() {
      const params = this.queryInfo
      const { data: res } = await this.$http.post('/sys-router/page', params)
      if (res.code === 20000) {
        this.userList = res.data.records
        this.total = parseInt(res.data.total)
      } else {
        this.$message.error(res.msg)
      }
    },
    // 递归处理非树形结构次联
      addUriAndRename(data, uri) {
      return data.map(item => {
        const newItem = {
          ...item,
          uri: uri || item.uri,
          controllerName: item.mappingName || item.controllerName,
          mappings: item.mappings ? this.addUriAndRename(item.mappings) : undefined
        };
        delete newItem.mappingName;
        return newItem;
      });
    },
    // Api接口信息 下拉列表
    async getUrlList() {
      const { data: res } = await this.$http.get('/home/apis')
      if (res.code === 20000) {
        this.UrlOptions = this.addUriAndRename(res.data, '/')
      }
    },
 
    // 权限集合 下拉列表
    async getRoleList() {
      const { data: res } = await this.$http.get('/sys-menu/tree')
      if (res.code === 20000) {
        // console.log(this.queryParams);
        this.listOptions = res.data
      }
    },
    // 监听 switch 开关的状态
    async userStateChanged(userInfo) {
      const { data: res } = await this.$http.put(
        `user/${userInfo.id}/state/${userInfo.state}`
      )
      if (res.code === 200) {
        userInfo.state = !userInfo.state
        return this.$message.error('更新用户状态失败!')
      }
      this.$meassage.success('更新用户状态成功!')
    },
    // 搜索按钮操作
    handleQuery() {
      this.queryInfo.currentPage = 1
      this.getList()
    },
    // 重置按钮操作
    resetQuery() {
      // this.resetForm('queryForm')
      // console.log(this) this指向$refs的是通过ref获得的实例对象loginFormRef
      this.$refs.queryForm.resetFields()
      this.handleQuery()
    },
    // 监听 pageSize 改变的事件
    handleSizeChange(newSize) {
      console.log(newSize)
      this.queryInfo.pageSize = newSize
      this.getList()
    },
    // 监听页码值改变的事件
    handleCurrentChange(newPage) {
      console.log(newPage)
      this.queryInfo.currentPage = newPage
      this.getList()
    },
    // 监听添加用户对话框关闭事件
    addDialogClosed() {
      // 重置表单
      this.$refs['addFormRef'].resetFields()
      this.routerId = undefined
      this.addForm = {
        isExclude: '',
        checkStrategy: '',
      }
    },
    // 新增按钮
    addTaskHandle() {
      this.getUrlList()
      this.dialogVisible = true
      this.upload.title = '添加路由'
    },
    // 修改按钮
    updateTaskHandle(row) {
      this.getUrlList()
      this.dialogVisible = true
      this.upload.title = '修改路由'
      this.addForm = {
        uri: row.uri,
        isExclude: row.isExclude,
        checkStrategy: row.checkStrategy,
        remark: row.remark,
        permissions:[row.permissions],
        routerId : row.routerId
      }
      //取row.permissions数组的最后一位
      this.routerId = row.routerId
    },
    // 多选按钮 修改
    async updateTasksHandle() {
      this.dialogVisible = true
      this.upload.title = '修改路由'
      this.addForm = this.rowData[0]
    },

    // 数组去重
    unique(arr) {
      var newArr = []
      for (var i = 0; i < arr.length; i++) {
        if (newArr.indexOf(arr[i]) === -1) {
          newArr.push(arr[i])
        }
      }
      return newArr
    },

    // 提交按钮 添加修改路由
    addUser() {
      console.log(this.addForm);
      this.$refs['addFormRef'].validate(async valid => {
    if (valid) {
      if (this.addForm.isExclude=='n') {
        let arr = [];
        this.addForm.permissions.map(item => {
          arr.push(...item);
        });
          if (this.routerId !== undefined) {
            this.addForm.permissions = this.unique(arr);
            // this.addForm.uri = this.addForm.uri[1];
            //如果this.addForm.uri是一个数组 那么参数则取this.addForm.uri[1],如果为字符串则取this.addForm.uri
            let params;
              if (Array.isArray(this.addForm.uri) && this.addForm.uri.length > 1) {
                // 如果this.addForm.uri是数组且长度大于1，则取this.addForm.uri[1]
                params = {...this.addForm,uri:this.addForm.uri[1] };
              } else if (typeof this.addForm.uri === 'string') {
                // 如果this.addForm.uri是字符串，则取this.addForm.uri
                params = { ...this.addForm,uri:this.addForm.uri };
              }
            const { data: res } = await this.$http.post(
              '/sys-router/update',
              params
            );
            if (res.code === 20000) {
              this.$message.success(`修改成功!`);
              this.getList();
              this.$refs.addFormRef.resetFields();
              this.dialogVisible = false;
              this.routerId = undefined;
            } else {
              this.$message.error(res.msg);
            }
          } else {
            this.addForm.permissions = this.unique(arr);
            // this.addForm.uri = this.addForm.uri[1];
            const params ={ ...this.addForm,uri:this.addForm.uri[1]};
            const { data: res } = await this.$http.post(
              '/sys-router/insert',
              params
            );
            if (res.code === 20000) {
              this.$message.success(`新增成功!`);
              this.getList();
              this.dialogVisible = false;
              this.routerId = undefined;
              this.$refs.addFormRef.resetFields();
            } else {
              this.$message.error(res.msg);
            }
          }
      } else{
          if (this.routerId !== undefined) {
            // this.addForm.uri = this.addForm.uri[1];
            // console.log(this.unique(arr));
            let params;
              if (Array.isArray(this.addForm.uri) && this.addForm.uri.length > 1) {
                // 如果this.addForm.uri是数组且长度大于1，则取this.addForm.uri[1]
                params = {
                  routerId: this.routerId,
                  isExclude: this.addForm.isExclude,
                  remark: this.addForm.remark,
                  uri:this.addForm.uri[1] 
                };
              } else if (typeof this.addForm.uri === 'string') {
                // 如果this.addForm.uri是字符串，则取this.addForm.uri
                params = { 
                  routerId: this.routerId,
                  isExclude: this.addForm.isExclude,
                  remark: this.addForm.remark,
                  uri:this.addForm.uri };
              }
            const { data: res } = await this.$http.post(
              '/sys-router/update',
              params
            );
            if (res.code === 20000) {
              this.$message.success(`修改成功!`);
              this.getList();
              this.$refs.addFormRef.resetFields();
              this.dialogVisible = false;
              this.routerId = undefined;
            } else {
              this.$message.error(res.msg);
            }
          } else {
            // this.addForm.uri = this.addForm.uri[1];
            const params ={ ...this.addForm,uri:this.addForm.uri[1]};
            const { data: res } = await this.$http.post(
              '/sys-router/insert',
              params
            );
            if (res.code === 20000) {
              this.$message.success(`新增成功!`);
              this.getList();
              this.$refs.addFormRef.resetFields();
              this.dialogVisible = false;
              this.routerId = undefined;
            } else {
              this.$message.error(res.msg);
            }
          }
      }}
      });
    },
    // 单选 删除按钮
    // async deleteTaskHandle(row) {
    //   const routerId = row.routerId || this.ids
    //   const { data: res } = await this.$http.post('/sys-router/delete',
    //     [routerId]
    //   )
    //   console.log(res);
    //   if (res.code === 20000) {
    //     this.getList()
    //     return this.$message.success('删除成功')
    //   } else {
    //     this.$message.error(res.msg)
    //   }
    // },
    // 删除封装
    async deleteTaskHandle(row) {
      if (!(await this._box(row.routerId, 'post', '/sys-router/delete'))) return
    },
    // 批量删除 暂时不做
    // 批量导出 暂时不做
    // 日志

    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row)
        })
      } else {
        this.$refs.multipleTable.clearSelection()
      }
    },
    toggleAll() {
      this.$refs.multipleTable.toggleAllSelection()
    },
    handleSelectionChange(selection) {
      //选中的数据
      this.rowData = selection
      this.ids = selection.map(item => item.routerId)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    hanldeChangeCascader(){
      if (this.addForm.uri.length != 0) {     
        const arr = this.$refs['myCascader'].getCheckedNodes()[0].pathLabels
        //直接修改可能会破坏Vue的响应性系统，所以使用set方法
        // this.addForm.remark = arr[arr.length-1]
        this.$set(this.addForm, 'remark', arr[arr.length-1]);
      }
    },
  },

  mounted() { }
  // 组件方法
}
</script>

<style scoped lang="less">
// 表格样式
.el-table {
  margin-top: 15px;
  font-size: 12px;
}

.urlSpan {
  display: inline-block;
  width: 100%;
}
</style>
